import { FC, ReactElement, MouseEventHandler, useState } from "react";
import { Button as BinBtn } from "../BUI";
import styled from "styled-components";
import { CopySvg, SuccessSvg, ErrorSvg } from "../BUI/Icon";
import { copyToClipboard } from "../../utils";

interface IProps {}

const CopyButton: FC<IProps> = (): ReactElement => {
  const [success, setSuccess] = useState(true); //复制是否成功
  const [isCopy, setIsCopy] = useState(false);

  const onCopy: MouseEventHandler<HTMLButtonElement> = e => {
    let { innerText } = e.currentTarget.parentNode as HTMLElement;
    const text = innerText.slice(2);
    setIsCopy(true);
    setSuccess(copyToClipboard(text));
  };

  return (
    <Button onClick={onCopy}>
      {isCopy ? (
        success ? (
          <>
            <SuccessSvg />
            复制成功
          </>
        ) : (
          <>
            <ErrorSvg />
            复制失败
          </>
        )
      ) : (
        <>
          <CopySvg />
          复制
        </>
      )}
    </Button>
  );
};

export default CopyButton;

const Button = styled(BinBtn)`
  position: absolute;
  right: 10px;
  top: 10px;
  min-width: 50px;
  letter-spacing: 2px;

  svg {
    margin-right: 5px;
  }
`;
